import {
  ElButton,
  ElDialog,
  ElForm,
  ElInput,
  ElFormItem,
  ElDatePicker,
  type FormInstance,
  type FormRules,
  ElMessage
} from 'element-plus'
import { computed, defineComponent, onMounted, reactive, ref, watch, type PropType } from 'vue'

export interface CreateBooking {
  meetingRoomId: number | string
  startTime: null | number
  endTime: null | number
  note: string
  meetingRoomName: string
}

export default defineComponent({
  name: 'CreateBookingModal',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    modalInfo: {
      type: Object as PropType<Pick<CreateBooking, 'meetingRoomName' | 'meetingRoomId'>>,
      default: () => ({})
    }
  },

  emits: ['update:modelValue', 'on-ok'],
  setup(props, { emit, slots }) {
    /** Data */
    let formData = reactive<CreateBooking>({
      startTime: null,
      endTime: null,
      meetingRoomName: '',
      meetingRoomId: '',
      note: ''
    })
    const ruleFormRef = ref<FormInstance>()
    const rules = reactive<FormRules<CreateBooking>>({
      meetingRoomId: [{ required: true, message: '请输入会议室名称', trigger: 'blur' }],
      startTime: [{ required: true, type: 'date', message: '请选择开始时间', trigger: 'change' }],
      endTime: [{ required: true, type: 'date', message: '请选择结束时间', trigger: 'change' }]
    })

    onMounted(() => {
      if (props.modalInfo) {
        Object.assign(formData, props.modalInfo)
      }
    })
    // 监听 modalInfo 的变化，并更新 formData
    watch(
      () => props.modalInfo,
      (newVal) => {
        Object.assign(formData, newVal)
      },
      { immediate: true, deep: true }
    )

    /** Events */
    const handleClose = () => {
      emit('update:modelValue', false)
    }
    const handleOk = async (formEl: FormInstance | undefined) => {
      if (!formEl) return

      await formEl.validate(async (valid, fields) => {
        if (valid) {
          emit('on-ok', formData)
          emit('update:modelValue', false)
        } else {
          ElMessage.error('表单校验失败')
        }
      })
    }
    const renderFooter = () => (
      <div class="fcc">
        <ElButton onClick={handleClose}>取消</ElButton>
        <ElButton type="primary" onClick={() => handleOk(ruleFormRef.value)}>
          确定
        </ElButton>
      </div>
    )

    return () => (
      <>
        <ElDialog
          modelValue={props.modelValue}
          title="创建预定"
          onClose={handleClose}
          v-slots={{ footer: renderFooter }}
          width={'480px'}
        >
          <ElForm ref={ruleFormRef} model={formData} label-width="auto" rules={rules}>
            <ElFormItem label="会议室名称" prop="meetingRoomId">
              <ElInput v-model={formData.meetingRoomName} disabled />
            </ElFormItem>
            <ElFormItem label="开始时间" prop="startTime">
              <ElDatePicker
                v-model={formData.startTime}
                type="datetime"
                value-format="x"
                style={{ flex: 1 }}
              />
            </ElFormItem>
            <ElFormItem label="结束时间" prop="endTime">
              <ElDatePicker
                v-model={formData.endTime}
                type="datetime"
                value-format="x"
                style={{ flex: 1 }}
              />
            </ElFormItem>
            <ElFormItem label="备注" prop="note">
              <ElInput v-model={formData.note} type="textarea" />
            </ElFormItem>
          </ElForm>
        </ElDialog>
      </>
    )
  }
})
